package com.example.dockercompose.dao;

import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisConnectionStateAdapter;
import io.lettuce.core.RedisURI;
import io.lettuce.core.codec.ByteArrayCodec;
import io.lettuce.core.pubsub.RedisPubSubAdapter;
import io.lettuce.core.pubsub.StatefulRedisPubSubConnection;
import io.lettuce.core.pubsub.api.sync.RedisPubSubCommands;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Redis {
    private static final Logger logger = LoggerFactory.getLogger(Redis.class);

    private static  RedisClient redisClient;

    public static void createRedisClient() {
        RedisURI redisURI = RedisURI.Builder.redis("redis", 6379).withPassword("jnrtk").withDatabase(0).build();
        redisClient = RedisClient.create(redisURI);
    }

    public void pubSub() {
        StatefulRedisPubSubConnection<byte[], byte[]> subConnection = connection(redisClient);
        RedisPubSubCommands<byte[], byte[]> sub = subConnection.sync();
        sub.subscribe("test".getBytes());
        subConnection.addListener(new RedisPubSubAdapter<>() {
            @Override
            public void message(byte[] channel, byte[] byteArray) {
                logger.info("redis sub {}, message: {}", new String(channel), new String(byteArray));
            }
        });

        RedisPubSubCommands<byte[], byte[]> sync = connection(redisClient).sync();
        sync.publish("test".getBytes(), "test".getBytes());
        logger.info("publish ok");
    }

    public StatefulRedisPubSubConnection<byte[], byte[]> connection(RedisClient redisClient) {
        return redisClient.connectPubSub(new ByteArrayCodec());
    }
}
